import type { AxiosResponse } from 'axios';
import axios from 'axios';

import { Logger } from '@/components/useLogger';

// 常量定义
const API_URL = 'http://127.0.0.1:51235/alpha';
const HEADERS = {
  'Content-Type': 'application/x-www-form-urlencoded',
};

// 定义接口
interface ApiResponse {
  errorCode: number;
  function: string;
  rtn: number;
}

interface EnumDeviceResponse extends ApiResponse {
  array: string;
}

// 将 JSON 对象转换为符合要求的格式
function toCustomUrlEncoded(payload: object): string {
  return 'json=' + JSON.stringify(payload);
}

// 通用请求函数
export async function makeRequest(payload: object): Promise<any> {
  try {
    const response: AxiosResponse<any> = await axios.post(
      API_URL,
      toCustomUrlEncoded(payload),
      { headers: HEADERS },
    );
    if (response.status === 200) {
      return response.data;
    } else {
      throw new Error(`usbKey请求失败，状态码: ${response.status}`);
    }
  } catch (error) {
    Logger('usbKey请求出错:', error);
    throw error;
  }
}

// 查找设备列表前置1
export async function loadLibrary(
  winDllName: string,
  linuxSOName: string,
  macDylibName: string,
): Promise<any> {
  const payload = {
    function: 'SOF_LoadLibrary',
    winDllName: winDllName,
    linuxSOName: linuxSOName,
    macDylibName: macDylibName,
  };
  return await makeRequest(payload);
}

// 查找设备列表 枚举设备
export async function enumDevice(): Promise<EnumDeviceResponse> {
  const payload = {
    function: 'SOF_EnumDevice',
  };
  return await makeRequest(payload);
}

// 获取设备实例, 判断errorCode是否为0
export async function getDeviceInstance(
  deviceName: string,
  applicationName: string,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_GetDeviceInstance',
    deviceName: deviceName,
    applicationName: applicationName,
  };
  return await makeRequest(payload);
}

// 设备认证
export async function devAuth(
  deviceName: string,
  authPassWd: string,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_DevAuth',
    deviceName: deviceName,
    authPassWd: authPassWd,
  };
  return await makeRequest(payload);
}

// 获取应用
export async function getApplicationList(
  deviceName: string,
): Promise<EnumDeviceResponse> {
  const payload = {
    function: 'SOF_GetApplicationList',
    deviceName: deviceName,
  };
  return await makeRequest(payload);
}

// 删除应用
export async function deleteApplication(
  deviceName: string,
  applicationName: string,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_DeleteApplication',
    deviceName: deviceName,
    applicationName: applicationName,
  };
  return await makeRequest(payload);
}

// 创建应用
export async function createApplication(
  deviceName: string,
  applicationName: string,
  soPin: string,
  soPinRetryCount: number,
  userPin: string,
  userPinRetryCount: number,
  rights: number,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_CreateApplication',
    deviceName: deviceName,
    applicationName: applicationName,
    soPin: soPin,
    soPinRetryCount: soPinRetryCount,
    userPin: userPin,
    userPinRetryCount: userPinRetryCount,
    rights: rights,
  };

  return await makeRequest(payload);
}

// 验证pin码
export async function loginSoPin(
  deviceName: string,
  passWd: string,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_LoginSoPin',
    deviceName: deviceName,
    passWd: passWd,
  };

  return await makeRequest(payload);
}

// 验证用户密码
export async function login(deviceName: string, passWd: string): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_Login',
    deviceName: deviceName,
    passWd: passWd,
  };

  return await makeRequest(payload);
}

// 创建容器
export async function createContainer(
  deviceName: string,
  containerName: string,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_CreateContainer',
    deviceName: deviceName,
    containerName: containerName,
  };

  return await makeRequest(payload);
}

// 定义接口
interface EnumCertContainerResponse extends ApiResponse {
  containerName: string;
}

// 获取容器名
export async function enumCertContainer(
  deviceName: string,
): Promise<EnumCertContainerResponse> {
  const payload = {
    function: 'SOF_EnumCertContiner',
    deviceName: deviceName,
  };

  return await makeRequest(payload);
}

// 生成密钥对
export async function createKeyPair(
  containerName: string,
  keySpec: number,
  asymAlg: number,
  ulKeyLength: number,
): Promise<ApiResponse> {
  const payload = {
    function: 'SOF_CreateKeyPair',
    containerName: containerName,
    keySpec: keySpec,
    asymAlg: asymAlg,
    keyLength: ulKeyLength,
  };

  return await makeRequest(payload);
}

// 导出公钥 获取Base64编码的公钥
export async function exportPubKey(
  containerName: string,
  deviceName: string,
  keySpec: number,
  expType: number,
): Promise<any> {
  const payload = {
    function: 'SOF_ExportPubKeyEx',
    deviceName: deviceName,
    containerName: containerName,
    keySpec: keySpec,
    expType: expType,
  };

  return await makeRequest(payload);
}

// 生成随机数
export async function generateRandom(
  deviceName: string,
  inDataLen: number,
): Promise<any> {
  const payload = {
    function: 'SOF_GenRandom',
    deviceName: deviceName,
    inDataLen: inDataLen,
  };

  return await makeRequest(payload);
}

// 对数据做摘要
export async function digestData(
  deviceName: string,
  containerName: string,
  inData: string,
  inDataLen: number,
): Promise<any> {
  const payload = {
    function: 'SOF_DigestData',
    deviceName: deviceName,
    containerName: containerName,
    inData: inData,
    inDataLen: inDataLen,
  };

  return await makeRequest(payload);
}

// 设置摘要算法USER ID - 适用于SM3 SM2
export async function setUserID(deviceName: string, userID: string): Promise<any> {
  const payload = {
    function: 'SOF_SetUserID',
    deviceName: deviceName,
    userID: userID,
  };

  return await makeRequest(payload);
}

// SetDigestMethod
export async function setDigestMethod(
  deviceName: string,
  digestMethod: number,
): Promise<any> {
  const payload = {
    function: 'SOF_SetDigestMethod',
    deviceName: deviceName,
    digestMethod: digestMethod,
  };

  return await makeRequest(payload);
}

// 对数据做签名
export async function signData(
  deviceName: string,
  containerName: string,
  keySpec: number,
  inData: string,
  inDataLen: number,
  mode: number, // 是否预处理 0: 预处理 1: 不预处理
): Promise<any> {
  const payload = {
    function: 'SOF_SignDataEx',
    deviceName: deviceName,
    containerName: containerName,
    keySpec: keySpec,
    inData: inData,
    inDataLen: inDataLen,
    mode: mode,
  };

  return await makeRequest(payload);
}

// 验证签名
export async function verifySignedData(
  deviceName: string,
  digestMethod: number,
  pubKey: string,
  inData: string,
  signedValue: string,
): Promise<any> {
  const payload = {
    function: 'SOF_PublicVerify',
    deviceName: deviceName,
    digestMethod: digestMethod,
    pubKey: pubKey,
    inData: inData,
    signedValue: signedValue,
  };

  return await makeRequest(payload);
}

// 验证签名
export async function verifySignedDataEx(
  deviceName: string,
  base64EncodeCert: string,
  digestMethod: number,
  inData: string,
  signedValue: string,
): Promise<any> {
  const payload = {
    function: 'SOF_VerifySignedDataEx',
    deviceName: deviceName,
    base64EncodeCert: base64EncodeCert,
    digestMethod: digestMethod,
    inData: inData,
    signedValue: signedValue,
  };

  return await makeRequest(payload);
}
